﻿using MultiDAQ_Analysis.Model;
using MultiDAQ_Analysis.test;
using MultiDAQ_Analysis.Util;
using MultiDAQ_Analysis.View;
using Newtonsoft.Json;
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Legends;
using OxyPlot.Series;
using OxyPlot.WindowsForms;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TickStyle = OxyPlot.Axes.TickStyle;

namespace MultiDAQ_Analysis.Forms
{
    /// <summary>
    /// ADC调试窗体 - α时间谱波形显示（单通道）
    /// </summary>
    public partial class AdcDebugForm : Form
    {
        #region 字段
        private PlotModel plotModel;           // 图表模型
        private LineSeries currentSeries;      // 当前通道的Series
        private CancellationTokenSource cancellationTokenSource;
        private bool isRunning = false;

        // α解析器
        private AlphaTimeSpectrumParser alphaParser;
        private System.Windows.Forms.Timer updateTimer;
        private UdpProtocolSender udpSender;

        // 配置 - 使用与 DeviceSettingsForm 相同的数据结构
        private List<ChannelData> channelDataList;
        private int channelCount;  // 从 AppConfig 读取

        // 自动停止
        private System.Windows.Forms.Timer autoStopTimer;
        private DateTime startTime;

        // 配置参数
        private const int MAX_DISPLAY_POINTS = 50000;
        private const int UPDATE_INTERVAL_MS = 100;
        #endregion

        #region 构造函数
        public AdcDebugForm()
        {
            InitializeComponent();
            channelCount = AppConfig.ChannelCount;  // 从 AppConfig 读取通道数
            LoadConfiguration();
            InitializeChannelComboBox();  // 初始化通道下拉框
            InitializePlot();
            InitializeUdpSender();
            InitializeAlphaParser();
        }
        #endregion

        #region 初始化方法
        /// <summary>
        /// 初始化通道下拉框
        /// </summary>
        private void InitializeChannelComboBox()
        {
            cmbChannel.Items.Clear();
            for (int i = 0; i < channelCount; i++)
            {
                cmbChannel.Items.Add($"通道 {i + 1}");
            }
            cmbChannel.SelectedIndex = 0;  // 默认选择通道1

            // 监听通道切换事件
            cmbChannel.SelectedIndexChanged += CmbChannel_SelectedIndexChanged;

            // 加载默认通道的起始阈值
            LoadStartThresholdForSelectedChannel();
        }

        /// <summary>
        /// 通道切换事件 - 更新起始阈值显示
        /// </summary>
        private void CmbChannel_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!isRunning)  // 只在非运行状态下允许切换
            {
                LoadStartThresholdForSelectedChannel();
            }
        }

        /// <summary>
        /// 加载选中通道的起始阈值配置
        /// </summary>
        private void LoadStartThresholdForSelectedChannel()
        {
            if (cmbChannel.SelectedIndex >= 0 && cmbChannel.SelectedIndex < channelDataList.Count)
            {
                int channelIndex = cmbChannel.SelectedIndex;
                double alphaHigh = channelDataList[channelIndex].Thresholds.AlphaHigh;
                txtStartThreshold.Text = alphaHigh.ToString("0.###");

                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"[ADC调试] 加载通道{channelIndex + 1}的起始阈值: {alphaHigh:F4}V");
                }
            }
        }

        /// <summary>
        /// 保存当前起始阈值到配置文件
        /// </summary>
        private bool SaveStartThresholdToConfig()
        {
            try
            {
                if (cmbChannel.SelectedIndex < 0 || cmbChannel.SelectedIndex >= channelDataList.Count)
                    return false;

                if (!double.TryParse(txtStartThreshold.Text, out double startThreshold))
                    return false;

                int channelIndex = cmbChannel.SelectedIndex;

                // 更新配置数据
                channelDataList[channelIndex].Thresholds.AlphaHigh = startThreshold;
                channelDataList[channelIndex].LastModified = DateTime.Now;

                // 保存到文件
                bool saved = ChannelDataManager.SaveAllChannelData(channelDataList);

                if (saved && AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"[ADC调试] 通道{channelIndex + 1}的起始阈值已保存: {startThreshold:F4}V");
                }

                return saved;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADC调试] 保存起始阈值失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 初始化绘图模型 - 单通道显示
        /// </summary>
        private void InitializePlot()
        {
            var colors = AppConfig.GetOxyChannelColors();

            // 创建PlotModel
            plotModel = new PlotModel
            {
                Title = "α时间谱波形显示（单通道）",
                TitleFontSize = 13,
                IsLegendVisible = false,  // 单通道不需要图例
                Background = OxyColors.White,
                PlotAreaBorderColor = OxyColors.Transparent,
                PlotAreaBorderThickness = new OxyThickness(0)
            };

            // X轴配置 - 纳秒单位
            var xAxis = new LinearAxis
            {
                Position = AxisPosition.Bottom,
                Title = "时间 (ns)",
                TitleFontSize = 12,
                Minimum = 0,
                AbsoluteMinimum = 0,
                MajorGridlineStyle = LineStyle.Solid,
                MajorGridlineColor = OxyColors.LightGray,
                MinorGridlineStyle = LineStyle.Dot,
                MinorGridlineColor = OxyColors.LightGray,
                TickStyle = TickStyle.Outside,
                StringFormat = "0",
                MajorStep = 4,
                IsPanEnabled = false
            };
            plotModel.Axes.Add(xAxis);

            // Y轴配置 - 频率显示
            var yAxis = new LinearAxis
            {
                Position = AxisPosition.Left,
                Title = "频率",
                TitleFontSize = 12,
                Minimum = 0,
                AbsoluteMinimum = 0,
                MajorGridlineStyle = LineStyle.Solid,
                MajorGridlineColor = OxyColors.LightGray,
                MinorGridlineStyle = LineStyle.Dot,
                MinorGridlineColor = OxyColors.LightGray,
                IsZoomEnabled = true,
                IsPanEnabled = true,
                TickStyle = TickStyle.Outside,
                StringFormat = "0"
            };
            plotModel.Axes.Add(yAxis);

            // 创建单个通道的LineSeries
            currentSeries = new LineSeries
            {
                Title = "通道波形",
                Color = colors[0],
                StrokeThickness = 2,
                LineStyle = LineStyle.Solid,
                MarkerType = MarkerType.None,
                TrackerFormatString = "时间: {2:F2}ns\n频率: {4:F0}",
                MinimumSegmentLength = 1
            };

            plotModel.Series.Add(currentSeries);

            // 绑定到PlotView
            plotView.Model = plotModel;
        }



        /// <summary>
        /// 初始化UDP发送器
        /// </summary>
        private void InitializeUdpSender()
        {
            try
            {
                udpSender = MainForm.getUdpSender();

                if (udpSender == null)
                {
                    udpSender = new UdpProtocolSender();
                    udpSender.OnLogMessage += msg => System.Diagnostics.Debug.WriteLine($"[ADC调试-发送] {msg}");
                    udpSender.OnErrorMessage += err => System.Diagnostics.Debug.WriteLine($"[ADC调试-错误] {err}");
                }

                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine("[ADC调试] UDP发送器初始化成功");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"UDP发送器初始化失败: {ex.Message}", "初始化错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 初始化α解析器
        /// </summary>
        private void InitializeAlphaParser()
        {
            alphaParser = new AlphaTimeSpectrumParser
            {
                MaxWaveformPoints = 10000,
            };

            // 从配置加载所有通道的α高阈值
            LoadThresholdsToParser();

            // 创建UI更新定时器
            updateTimer = new System.Windows.Forms.Timer
            {
                Interval = UPDATE_INTERVAL_MS
            };
            updateTimer.Tick += UpdateTimer_Tick;

            // 创建自动停止定时器
            autoStopTimer = new System.Windows.Forms.Timer
            {
                Interval = 100  // 每100ms检查一次
            };
            autoStopTimer.Tick += AutoStopTimer_Tick;

            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine("[ADC调试] α解析器初始化成功");
            }
        }

        /// <summary>
        /// 加载设备配置（包含α高阈值 - 时间谱脉宽起始阈值）
        /// </summary>
        private void LoadConfiguration()
        {
            try
            {
                // 从文件加载所有通道数据（与 DeviceSettingsForm 相同的方式）
                channelDataList = ChannelDataManager.LoadAllChannelData();

                // 确保有足够的通道数据
                while (channelDataList.Count < channelCount)
                {
                    channelDataList.Add(new ChannelData { ChannelIndex = channelDataList.Count });
                }

                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine("[ADC调试] 配置文件加载成功");
                    for (int i = 0; i < channelDataList.Count && i < channelCount; i++)
                    {
                        var ch = channelDataList[i];
                        Console.WriteLine($"  通道{i + 1} α高阈（时间谱脉宽起始阈值）: {ch.Thresholds.AlphaHigh:F4}V");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADC调试] 配置加载失败: {ex.Message}");
                InitializeDefaultData();
            }
        }

        /// <summary>
        /// 创建默认配置数据（与 DeviceSettingsForm 相同的方式）
        /// </summary>
        private void InitializeDefaultData()
        {
            channelDataList = new List<ChannelData>();
            for (int i = 0; i < channelCount; i++)
            {
                var channelData = new ChannelData
                {
                    ChannelIndex = i,
                    StepLength = 4.0  // 默认4ns
                };
                channelData.Thresholds.AlphaHigh = 0.5;   // 默认α高阈 0.5V
                channelData.Thresholds.AlphaLow = 0.0;
                channelData.Thresholds.BetaLow = 0.0;
                channelData.Thresholds.BetaHigh = 1.0;
                channelData.Thresholds.TriggerLine = 0.1;
                channelData.Thresholds.IsSelected = true;

                channelDataList.Add(channelData);
            }

            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine("[ADC调试] 使用默认配置");
            }
        }

        /// <summary>
        /// 将配置中的α高阈值加载到解析器
        /// </summary>
        private void LoadThresholdsToParser()
        {
            if (channelDataList == null) return;

            for (int i = 0; i < channelDataList.Count && i < channelCount; i++)
            {
                int channelNumber = i + 1;
                double alphaHigh = channelDataList[i].Thresholds.AlphaHigh;
                alphaParser.SetChannelThreshold(channelNumber, alphaHigh);

                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"[ADC调试] 通道{channelNumber} 阈值: {alphaHigh:F4}V");
                }
            }
        }



        #endregion

        #region 事件处理
        /// <summary>
        /// 启动/停止按钮点击事件
        /// </summary>
        private void BtnStart_Click(object sender, EventArgs e)
        {
            if (isRunning)
            {
                StopSampling();
                return;
            }

            // 验证输入 - 采样时长
            if (!double.TryParse(txtSamplingDuration.Text, out double samplingDuration) ||
                samplingDuration <= 0)
            {
                MessageBox.Show("请输入有效的采样时长（正数）", "输入错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 验证输入 - 脉宽配置
            if (!double.TryParse(txtPulseWidth.Text, out double pulseWidth) ||
                pulseWidth <= 0)
            {
                MessageBox.Show("请输入有效的脉宽配置（正数）", "输入错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 验证输入 - 起始阈值
            if (!double.TryParse(txtStartThreshold.Text, out double startThreshold))
            {
                MessageBox.Show("请输入有效的起始阈值", "输入错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 获取选中的通道
            if (cmbChannel.SelectedIndex < 0)
            {
                MessageBox.Show("请选择一个通道", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            int selectedChannel = cmbChannel.SelectedIndex + 1;  // 通道从1开始

            // 保存起始阈值到配置文件（实现双向绑定）
            if (!SaveStartThresholdToConfig())
            {
                MessageBox.Show("保存起始阈值配置失败", "警告",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                // 继续执行，不中断启动流程
            }

            // 设置选中通道的阈值到解析器
            alphaParser.SetChannelThreshold(selectedChannel, startThreshold);

            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine($"\n=== ADC调试启动 ===");
                Console.WriteLine($"采样时长: {samplingDuration:F3}s");
                Console.WriteLine($"脉宽配置: {pulseWidth}ns");
                Console.WriteLine($"选中通道: {selectedChannel}");
                Console.WriteLine($"起始阈值: {startThreshold:F3}V（已保存到配置）");
            }

            // 发送UDP协议到硬件
            if (udpSender != null)
            {
                try
                {
                    // 1. 将采样时长（秒）转换为纳秒
                    double timeNs = samplingDuration * 1_000_000_000.0;

                    // 2. 发送时间谱脉宽测试时间
                    bool timeSent = udpSender.SendPulseWidthTestTime(timeNs);

                    if (!timeSent)
                    {
                        MessageBox.Show("发送采样时长失败，请检查设备连接", "发送失败",
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    System.Threading.Thread.Sleep(50);

                    // 3. 发送启动请求
                    bool startSent = udpSender.SendPulseWidthTestStartRequest(true);

                    if (!startSent)
                    {
                        MessageBox.Show("发送启动信号失败，请检查设备连接", "发送失败",
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    System.Diagnostics.Debug.WriteLine($"UDP协议发送成功");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发送协议失败: {ex.Message}", "发送错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            else
            {
                MessageBox.Show("UDP发送器未初始化", "初始化错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 记录启动时间，用于自动停止
            startTime = DateTime.Now;

            // 启动解析器和UI更新
            alphaParser.Start();
            updateTimer.Start();
            autoStopTimer.Start();  // 启动自动停止定时器

            // 更新界面状态
            isRunning = true;
            btnStart.Text = "停止";
            btnStart.BackColor = Color.OrangeRed;
            txtSamplingDuration.Enabled = false;
            txtPulseWidth.Enabled = false;
            cmbChannel.Enabled = false;
            txtStartThreshold.Enabled = false;
            lblStatus.Text = $"正在采集 (通道{selectedChannel}) - 将在{samplingDuration:F1}秒后自动停止";
            lblStatus.ForeColor = Color.Green;

            // 清空图表数据
            currentSeries.Points.Clear();
            plotView.InvalidatePlot(true);

            cancellationTokenSource = new CancellationTokenSource();

            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine($"启动时间: {startTime:HH:mm:ss}");
                Console.WriteLine($"预计停止时间: {startTime.AddSeconds(samplingDuration):HH:mm:ss}");
                Console.WriteLine("等待硬件数据...");
            }
        }

        /// <summary>
        /// 定时从解析器获取波形并更新图表
        /// </summary>
        private void UpdateTimer_Tick(object sender, EventArgs e)
        {
            if (!isRunning) return;

            var waveforms = alphaParser.GetAllWaveforms();
            if (waveforms.Count == 0) return;

            const int MAX_POINTS_PER_CHANNEL = 50000;
            int selectedChannel = cmbChannel.SelectedIndex + 1;
            double pulseWidth = double.Parse(txtPulseWidth.Text);

            // 检查并清理数据点
            if (currentSeries.Points.Count > MAX_POINTS_PER_CHANNEL)
            {
                int removeCount = currentSeries.Points.Count / 2;
                for (int i = 0; i < removeCount; i++)
                {
                    currentSeries.Points.RemoveAt(0);
                }
                Console.WriteLine($"[ADC调试] 数据点过多，已清理 {removeCount} 个旧点");
            }

            // 只处理选中通道的波形数据
            int waveformCount = 0;
            foreach (var waveform in waveforms)
            {
                if (waveform.ChannelNumber != selectedChannel) continue;

                waveformCount++;

                // 遍历电压数据，使用配置的脉宽间隔
                for (int i = 0; i < waveform.Voltages.Length; i++)
                {
                    double timeNs = i * pulseWidth;  // 使用配置的脉宽
                    double voltage = waveform.Voltages[i];

                    // 验证数据有效性
                    if (double.IsNaN(voltage) || double.IsInfinity(voltage))
                    {
                        continue;
                    }

                    // 验证数据范围
                    if (voltage < 0)
                    {
                        Console.WriteLine($"[ADC调试-警告] 频率值异常: 时间={timeNs}ns, 频率={voltage}");
                        continue;
                    }

                    currentSeries.Points.Add(new DataPoint(timeNs, voltage));
                }

                // 在波形之间添加断点（用于视觉分隔）
                if (waveform != waveforms.Last())
                {
                    currentSeries.Points.Add(new DataPoint(double.NaN, double.NaN));
                }
            }

            // 更新状态显示
            if (waveformCount > 0)
            {
                double remainingSeconds = (startTime.AddSeconds(double.Parse(txtSamplingDuration.Text)) - DateTime.Now).TotalSeconds;
                if (remainingSeconds > 0)
                {
                    lblStatus.Text = $"已捕获波形 [通道{selectedChannel}:{waveformCount}个] - 剩余{remainingSeconds:F1}秒";
                }
            }

            // 刷新图表
            try
            {
                plotView.InvalidatePlot(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADC调试-错误] 图表刷新失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 自动停止定时器检查
        /// </summary>
        private void AutoStopTimer_Tick(object sender, EventArgs e)
        {
            if (!isRunning) return;

            // 检查是否达到设定的采样时长
            if (double.TryParse(txtSamplingDuration.Text, out double samplingDuration))
            {
                double elapsed = (DateTime.Now - startTime).TotalSeconds;

                // 如果经过的时间超过设定时长，自动停止
                if (elapsed >= samplingDuration)
                {
                    if (AppConfig.LogPrint == 1)
                    {
                        Console.WriteLine($"\n[ADC调试] 达到设定采样时长({samplingDuration:F1}秒)，自动停止");
                        Console.WriteLine($"实际运行时间: {elapsed:F3}秒");
                    }

                    StopSampling();
                }
            }
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        private void AdcDebugForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            StopSampling();

            // 释放定时器资源
            updateTimer?.Stop();
            updateTimer?.Dispose();
            autoStopTimer?.Stop();
            autoStopTimer?.Dispose();

            // 释放解析器
            alphaParser?.Dispose();

            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine("[ADC调试] 窗体已关闭");
            }
        }
        #endregion

        #region 采样控制
        /// <summary>
        /// 停止采样
        /// </summary>
        private void StopSampling()
        {
            if (!isRunning) return;

            if (AppConfig.LogPrint == 1)
            {
                double elapsed = (DateTime.Now - startTime).TotalSeconds;
                Console.WriteLine($"\n[ADC调试] 正在停止... (运行时间: {elapsed:F3}秒)");
            }

            // 取消任务
            if (cancellationTokenSource != null)
            {
                cancellationTokenSource.Cancel();
            }

            // 停止解析器和所有定时器
            updateTimer.Stop();
            autoStopTimer.Stop();  // 停止自动停止定时器
            alphaParser.Stop();

            // 发送停止信号到硬件
            if (udpSender != null)
            {
                try
                {
                    udpSender.SendPulseWidthTestStartRequest(false);
                    System.Diagnostics.Debug.WriteLine("=== ADC调试停止信号已发送 ===");
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"停止信号发送失败: {ex.Message}");
                }
            }

            // 更新界面状态
            isRunning = false;
            btnStart.Text = "启动";
            btnStart.BackColor = SystemColors.Control;
            txtSamplingDuration.Enabled = true;
            txtPulseWidth.Enabled = true;
            cmbChannel.Enabled = true;
            txtStartThreshold.Enabled = true;
            lblStatus.Text = "已停止";
            lblStatus.ForeColor = Color.Red;

            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine("[ADC调试] 已停止");
            }
        }

        /// <summary>
        /// UDP数据接收回调（需要在UDP接收器中调用此方法）
        /// </summary>
        public void OnUdpDataReceived(byte[] data, int length)
        {
            if (alphaParser != null && isRunning)
            {
                alphaParser.EnqueueData(data, length);
            }
        }
        #endregion
    }
}
